/**
 *	HTTP封装，基于fetch
 */

import 'whatwg-fetch'
import 'es6-promise'

/**
 * 请求参数封装
 * @param  {[type]} paramsObj [description]
 * @return {[type]}           [description]
 */
 function getParams(paramsObj){
 	var params = ''
 	if (paramsObj) {
 		params += '?'
 		for(var key in paramsObj){
 			params += ( key +'='+ paramsObj[key] + '&' )
 		}
 	}
 	return params
 }
// import '../mock/wallet/data.js'
// 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式
function obj2params(obj) {
	var result = '';
	var item;
	for (item in obj) {
		result += '&' + item + '=' + encodeURIComponent(obj[item]);
	}

	if (result) {
		result = result.slice(1);
	}

	return result;
}
var http = {
	get : function get(url,paramsObj) {
		url +=  getParams(paramsObj)
		var result = fetch(url, {
			mode: "no-cors",
			credentials: 'include',
			headers: {
				'Accept': 'application/json, text/plain, */*',
				'Access-Control-Allow-Origin': '*',
			}
		});

		return result;
	},
	post :function (url,paramsObj,isForm) {
		var config = {
			method: 'POST',
			mode: "no-cors",
			credentials: 'include',
			headers: {
				'Accept': 'application/json, text/plain, */*',
				'Access-Control-Allow-Origin': '*',
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(paramsObj)
		}
		if (isForm) {
			config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
			config.body = obj2params(paramsObj)
		}
		var result = fetch(url, config);

		return result;
	}


}

export default http